/*
 * @Author: yangzonglong
 * @Date: 2021-02-22 13:56:10
 * @version: v1.0.0
 * @Descripttion: 
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-06-30 14:25:13
 * @Auditor: 
 */
import React, { useEffect, useState, useRef } from 'react';
import { Modal, Form, Select } from 'antd'
import { Table, units } from '@library'
import { TableRefProps } from '@library/components/table/interface'

interface SourceProps {
  filedCode: string;
  type: string;
  name: string;
  id: string;
}

interface Props {
  visible: boolean;
  onCancel: () => void;
  onOk: (rows: any[]) => void;
}

const columns = [
  { dataIndex: 'filedCode', title: '字段' },
  { dataIndex: 'name' },
  { dataIndex: 'type' }
]



const getSource = (v: any) => {
  const _keys = Object.keys(v)
  const _value = Object.values(v)
  return _value.map((item: any, index) => ({
    name: item.cn || item?.locales?.cn || _keys[index],
    id: _keys[index],
    filedCode: _keys[index],
    type: item.type,
  }))

}

const ModelForm = ({ visible, onOk, onCancel }: Props) => {

  const tableRef = useRef<TableRefProps>(null)
  const [value, setValue] = useState('')
  const [modelSource, setModelSource] = useState<string[]>([])
  const [dataSource, setDataSource] = useState<SourceProps[]>([])

  useEffect(() => {
    units.serverLoading('/bk/api/lowcode/getModels', {}).then(res => {
      setModelSource(res.models || [])
    })
  }, [])

  useEffect(() => {
    if (value) {
      tableRef.current?.onRefresh()
      units.serverLoading(`/bk/api/lowcode/${value}/getModel`, {}).then(res => {
        setDataSource(getSource(res.attributes || {}))
      })
    }
  }, [value])


  const _onOK = () => {
    setValue('')
    setDataSource([])
    const rows = tableRef.current?.getSelectedRows()
    onOk(rows || [])
  }
  const _onCancel = () => {
    setValue('')
    setDataSource([])
    onCancel()
  }

  return (
    <Modal destroyOnClose visible={visible} title='模型表单' width={600} onOk={_onOK} onCancel={_onCancel}>
      <Form>
        <Form.Item label='选择模型'>
          <Select
            value={value}
            onChange={setValue}>
            {modelSource.map(item => (
              <Select.Option key={item} value={item}>{item}</Select.Option>
            ))}
          </Select>
        </Form.Item>
      </Form>
      <div style={{ flexDirection: 'column', display: 'flex', maxHeight: '600px', overflow: 'auto' }}>
        <Table ref={tableRef} rowSelectionType='checkbox' flat dataSource={dataSource} columns={columns} />
      </div>

    </Modal>
  )
}

export default ModelForm;